"""
python fujian3_cal_average_inventory.py
"""

import os
import json
import re
import numpy as np

# 指定路径
input_directory = r'../fujian/fujian1/pmdarima_single_batch'
output_file_path = r'../fujian/fujian3/data_from_p1/all_average_inventory.json'

# 获取输出文件夹路径
output_directory = os.path.dirname(output_file_path)
if not os.path.exists(output_directory):
    os.makedirs(output_directory)


# 存储结果的列表
average_inventories = []

# 遍历输入目录
for filename in os.listdir(input_directory):
    # 使用正则表达式提取 category 编号
    match = re.search(r'category(\d+)', filename)
    if match:
        category_id = match.group(1)  # 获取类别编号

        # 构建文件路径
        file_path = os.path.join(input_directory, filename)

        # 读取 JSON 文件
        with open(file_path, 'r', encoding='utf-8') as file:
            data = json.load(file)
        
        # 提取库存数据
        inventories = [item['inventory'] for item in data]
        
        # 计算均值
        average_inventory = np.mean(inventories)
        
        # 将结果添加到列表中
        average_inventories.append({
            "category_id": category_id,
            "average_inventory": average_inventory
        })

# 输出到 JSON 文件
with open(output_file_path, 'w', encoding='utf-8') as output_file:
    json.dump(average_inventories, output_file, indent=4)

print("Average inventory calculated and saved to", output_file_path)
